/**
 * 自动刷新机制测试脚本
 * 用于验证环境切换后的数据同步是否正常工作
 */

const http = require('http');
const fs = require('fs');
const path = require('path');

// 测试配置
const TEST_CONFIG = {
  host: '127.0.0.1',
  port: 8899,
  basePath: '/plugin.nohost',
  testInterval: 1000, // 1秒间隔
  maxWaitTime: 10000  // 最大等待时间10秒
};

// 测试结果
let testResults = [];

/**
 * 发送API请求
 */
function makeApiRequest(path, method = 'GET', data = null) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: TEST_CONFIG.host,
      port: TEST_CONFIG.port,
      path: path,
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'User-Agent': 'NoHost-AutoRefresh-Test'
      }
    };

    const req = http.request(options, (res) => {
      let responseData = '';
      
      res.on('data', (chunk) => {
        responseData += chunk;
      });
      
      res.on('end', () => {
        try {
          const response = JSON.parse(responseData);
          resolve({
            status: res.statusCode,
            data: response,
            headers: res.headers
          });
        } catch (error) {
          resolve({
            status: res.statusCode,
            data: responseData,
            headers: res.headers
          });
        }
      });
    });

    req.on('error', (error) => {
      reject(new Error(`请求失败: ${error.message}`));
    });

    if (data) {
      req.write(JSON.stringify(data));
    }
    
    req.end();
  });
}

/**
 * 检查规则文件状态
 */
function checkRulesFile() {
  try {
    const rulesPath = path.join(__dirname, 'rules.txt');
    if (fs.existsSync(rulesPath)) {
      const stats = fs.statSync(rulesPath);
      const content = fs.readFileSync(rulesPath, 'utf8');
      return {
        exists: true,
        modifiedTime: stats.mtime,
        size: stats.size,
        hasActiveRules: content.includes('dgvip360.drivergenius3.com'),
        content: content.substring(0, 200)
      };
    }
    return { exists: false };
  } catch (error) {
    return { error: error.message };
  }
}

/**
 * 测试环境激活
 */
async function testEnvironmentActivation() {
  console.log('🔌 测试环境激活...');
  
  try {
    // 检查激活前的状态
    const beforeState = checkRulesFile();
    console.log(`   激活前规则状态: ${beforeState.hasActiveRules ? '有激活规则' : '无激活规则'}`);
    
    // 调用激活接口
    const response = await makeApiRequest(
      `${TEST_CONFIG.basePath}/cgi-bin/api/whistle/force-refresh`,
      'POST'
    );
    
    if (response.status === 200 && response.data.success) {
      console.log(`   ✅ 激活成功，响应时间: ${response.data.data?.responseTime || 'N/A'}ms`);
      
      // 等待规则生效
      await waitForRulesUpdate(beforeState.modifiedTime);
      
      // 检查激活后的状态
      const afterState = checkRulesFile();
      console.log(`   激活后规则状态: ${afterState.hasActiveRules ? '有激活规则' : '无激活规则'}`);
      
      testResults.push({
        test: '环境激活',
        status: '✅ 成功',
        beforeState: beforeState.hasActiveRules,
        afterState: afterState.hasActiveRules,
        responseTime: response.data.data?.responseTime
      });
      
    } else {
      console.log(`   ❌ 激活失败: ${response.data?.message || '未知错误'}`);
      testResults.push({
        test: '环境激活',
        status: '❌ 失败',
        error: response.data?.message
      });
    }
    
  } catch (error) {
    console.log(`   ❌ 激活测试错误: ${error.message}`);
    testResults.push({
      test: '环境激活',
      status: '❌ 错误',
      error: error.message
    });
  }
  
  console.log('');
}

/**
 * 测试环境取消激活
 */
async function testEnvironmentDeactivation() {
  console.log('🔌 测试环境取消激活...');
  
  try {
    // 检查取消激活前的状态
    const beforeState = checkRulesFile();
    console.log(`   取消激活前规则状态: ${beforeState.hasActiveRules ? '有激活规则' : '无激活规则'}`);
    
    // 调用取消激活接口
    const response = await makeApiRequest(
      `${TEST_CONFIG.basePath}/cgi-bin/api/whistle/force-refresh`,
      'POST'
    );
    
    if (response.status === 200 && response.data.success) {
      console.log(`   ✅ 取消激活成功，响应时间: ${response.data.data?.responseTime || 'N/A'}ms`);
      
      // 等待规则生效
      await waitForRulesUpdate(beforeState.modifiedTime);
      
      // 检查取消激活后的状态
      const afterState = checkRulesFile();
      console.log(`   取消激活后规则状态: ${afterState.hasActiveRules ? '有激活规则' : '无激活规则'}`);
      
      testResults.push({
        test: '环境取消激活',
        status: '✅ 成功',
        beforeState: beforeState.hasActiveRules,
        afterState: afterState.hasActiveRules,
        responseTime: response.data.data?.responseTime
      });
      
    } else {
      console.log(`   ❌ 取消激活失败: ${response.data?.message || '未知错误'}`);
      testResults.push({
        test: '环境取消激活',
        status: '❌ 失败',
        error: response.data?.message
      });
    }
    
  } catch (error) {
    console.log(`   ❌ 取消激活测试错误: ${error.message}`);
    testResults.push({
      test: '环境取消激活',
      status: '❌ 错误',
      error: error.message
    });
  }
  
  console.log('');
}

/**
 * 等待规则文件更新
 */
async function waitForRulesUpdate(originalTime) {
  console.log('   ⏳ 等待规则文件更新...');
  
  const startTime = Date.now();
  
  while (Date.now() - startTime < TEST_CONFIG.maxWaitTime) {
    const currentState = checkRulesFile();
    
    if (currentState.modifiedTime && currentState.modifiedTime > originalTime) {
      const waitTime = Date.now() - startTime;
      console.log(`   ✅ 规则文件已更新，等待时间: ${waitTime}ms`);
      return true;
    }
    
    // 等待一段时间后再次检查
    await new Promise(resolve => setTimeout(resolve, TEST_CONFIG.testInterval));
  }
  
  console.log(`   ⚠️ 等待超时 (${TEST_CONFIG.maxWaitTime}ms)`);
  return false;
}

/**
 * 测试自动刷新机制
 */
async function testAutoRefresh() {
  console.log('🚀 开始测试 NoHost 插件自动刷新机制...\n');
  console.log(`测试地址: http://${TEST_CONFIG.host}:${TEST_CONFIG.port}${TEST_CONFIG.basePath}\n`);
  
  // 检查初始状态
  console.log('📋 检查初始状态...');
  const initialState = checkRulesFile();
  if (initialState.exists) {
    console.log(`   规则文件存在: ${initialState.hasActiveRules ? '有激活规则' : '无激活规则'}`);
    console.log(`   文件大小: ${initialState.size} 字节`);
    console.log(`   最后修改: ${initialState.modifiedTime}`);
  } else {
    console.log('   规则文件不存在');
  }
  console.log('');
  
  // 执行测试
  await testEnvironmentActivation();
  await testEnvironmentDeactivation();
  
  // 输出测试结果
  printTestResults();
}

/**
 * 输出测试结果
 */
function printTestResults() {
  console.log('📊 自动刷新测试结果汇总:');
  console.log('='.repeat(60));
  
  testResults.forEach((result, index) => {
    console.log(`${index + 1}. ${result.test}`);
    console.log(`   状态: ${result.status}`);
    
    if (result.error) {
      console.log(`   错误: ${result.error}`);
    } else if (result.beforeState !== undefined) {
      console.log(`   状态变化: ${result.beforeState ? '有规则' : '无规则'} → ${result.afterState ? '有规则' : '无规则'}`);
      console.log(`   响应时间: ${result.responseTime || 'N/A'}ms`);
    }
    console.log('');
  });
  
  const successCount = testResults.filter(r => r.status.includes('✅')).length;
  const totalCount = testResults.length;
  
  console.log(`🎯 总体结果: ${successCount}/${totalCount} 项测试通过`);
  
  if (successCount === totalCount) {
    console.log('🎉 自动刷新机制工作正常！');
  } else {
    console.log('⚠️  部分测试失败，请检查相关配置');
  }
  
  // 提供建议
  if (successCount === 0) {
    console.log('\n🔧 调试建议:');
    console.log('1. 确保 Whistle 正在运行');
    console.log('2. 确保插件已正确安装和启用');
    console.log('3. 检查 rules.txt 文件是否存在');
    console.log('4. 查看 Whistle 控制台日志');
  }
}

// 运行测试
if (require.main === module) {
  testAutoRefresh().catch(console.error);
}

module.exports = { testAutoRefresh, testEnvironmentActivation, testEnvironmentDeactivation };
